<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/11/11
 * Time: 14:21
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use common\components\helpers\Util;
use common\models\datas\Cate;
use common\models\datas\Category;
use zhtfrontend\models\datas\ArrangeCourse;
use zhtfrontend\models\datas\Arrangement;
use zhtfrontend\models\datas\ClassLesson;
use zhtfrontend\models\datas\ClassManage;
use zhtfrontend\models\datas\LessonMedia;
use zhtfrontend\modules\sitepadapi\components\rest\ActiveController;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use common\models\datas\Customer;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\Course;
use zhtfrontend\models\datas\Student;
use yii\web\Response;

class GrowthlogController extends ActiveController
{
    public $modelClass = 'zhtfrontend\models\datas\ClassLesson';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        $behaviors['corsFilter'] = [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Allow-Origin' => ['*'],
                'Access-Control-Request-Method' => ['POST', 'PUT', 'GET', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With'],
                'Access-Control-Allow-Credentials' => true,
                'Access-Control-Max-Age' => 3600,
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],
        ];
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    public function actionView($lesson_id)
    {
        $data = $student = $isRefouce = $noRefouce = [];
        $currentData = $this->findModel($lesson_id);
        $current = ($currentData['lesson'] - 1 == 0) ? $currentData['lesson'] : $currentData['lesson'] - 1;
        $prevData = (new Query())->select('*')->from('{{%class_lesson}}')->where([
            'class_id' => $currentData['class_id'],
            'lesson' => $current,
            'ovo' => $currentData['ovo'],
        ])->one(Fun::getSiteDb());
        if ($currentData['ovo'] == 0) {
            $lessonStudent = (new Query())->select('*')->from('{{%student}} a')
                ->leftJoin('{{%lesson_student}} b', 'a.id=b.student_id')
                ->where(['b.lesson_id' => $prevData['lesson_id']])
                ->one(Fun::getSiteDb());
            $lessonMedia = (new Query())->select([
                'lm.lesson_id as lesson_id', 'lm.is_refouce as is_refouce', 'lm.student_id as student_id', 'lm.m_type as m_type',
                'm.file_path as url_path', 'lm.lesson_id as lesson_id'])
                ->from('{{%lesson_media}} lm')
                ->leftJoin('{{%medias}} m', 'lm.id=m.object_id')
                ->where(['lm.student_id' => $lessonStudent['student_id']])
                ->andWhere(['in', 'lm.lesson_id', [$prevData['lesson_id'], $lesson_id]])
                ->all(Fun::getSiteDb());
            if ($lesson_id == $prevData['lesson_id']) {
                foreach ($lessonMedia as $k => $v) {
                    switch ($v['is_refouce']) {
                        case 1:
                            $isRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            break;
                        case 0:
                            $noRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            break;
                    }
                }
            } else {
                foreach ($lessonMedia as $k => $v) {
                    switch ($v['is_refouce']) {
                        case 1:
                            if ($v['lesson_id'] == $lesson_id) {
                                $isRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            }
                            break;
                        case 0:
                            if ($v['lesson_id'] == $prevData['lesson_id']) {
                                $noRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            }
                            break;
                    }
                }
            }
            $data['items'][] = [
                'student_id' => $lessonStudent['student_id'],
                'student_name' => $lessonStudent['name'],
                'student_img' => $lessonStudent['img'],
                'url_paths' => empty($isRefouce[$lessonStudent['student_id']]) ? [] : $isRefouce[$lessonStudent['student_id']],
                'refouce_notice' => $lessonStudent['refouce_notice'],
                'content' => $this->getContent($lesson_id, $lessonStudent['student_id']),
                'file_path' => empty($noRefouce[$lessonStudent['student_id']]) ? [] : $noRefouce[$lessonStudent['student_id']]
            ];
            return $data;
        } else {
            $lessonStudent = (new Query())->select('*')->from('{{%student}} a')
                ->leftJoin('{{%lesson_student}} b', 'a.id=b.student_id')
                ->where(['b.lesson_id' => $prevData['lesson_id']])
                ->all(Fun::getSiteDb());
            $lessonMedia = (new Query())->select([
                'lm.lesson_id as lesson_id', 'lm.is_refouce as is_refouce', 'lm.student_id as student_id', 'lm.m_type as m_type',
                'm.file_path as url_path'])
                ->from('{{%lesson_media}} lm')
                ->leftJoin('{{%medias}} m', 'lm.id=m.object_id')
                ->where(['or', "lm.lesson_id={$lesson_id}", "lm.lesson_id={$prevData['lesson_id']}"])
                ->all(Fun::getSiteDb());
            if ($lesson_id == $prevData['lesson_id']) {
                foreach ($lessonMedia as $k => $v) {
                    switch ($v['is_refouce']) {
                        case 1:
                            $isRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            break;
                        case 0:
                            $noRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            break;
                    }
                }
            } else {
                foreach ($lessonMedia as $k => $v) {
                    switch ($v['is_refouce']) {
                        case 1:
                            if ($v['lesson_id'] == $lesson_id) {
                                $isRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            }
                            break;
                        case 0:
                            if ($v['lesson_id'] == $prevData['lesson_id']) {
                                $noRefouce[$v['student_id']][] = ['lesson_id' => $v['lesson_id'], 'm_type' => $v['m_type'], 'url_path' => $v['url_path']];
                            }
                            break;
                    }
                }
            }
            foreach ($lessonStudent as $kk => $vv) {
                $data['items'][] = [
                    'student_id' => $vv['student_id'],
                    'student_name' => $vv['name'],
                    'student_img' => $vv['img'],
                    'url_paths' => empty($isRefouce[$vv['student_id']]) ? [] : $isRefouce[$vv['student_id']],
                    'refouce_notice' => $vv['refouce_notice'],
                    'content' => $this->getContent($lesson_id, $vv['student_id']),
                    'file_path' => empty($noRefouce[$vv['student_id']]) ? [] : $noRefouce[$vv['student_id']],
                ];
            }
        }
        return $data;
    }


    public function actionFindbytid($teache_id)
    {
        $dataArr = $time = $item = [];
        $teache = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $teache_id])->one(Fun::getSiteDb());
        $arrangeCourse = (new Query())->select('id')->from('{{%arrange_course}}')->where([
            'teacher_id' => $teache['teacher_id']])->column(Fun::getSiteDb());
        $classManage = (new Query())->select('class_id')->from('{{%class_manage}}')->where([
            'in', 'code', $arrangeCourse])->column(Fun::getSiteDb());
        $query = (new Query())->select('*')->from('{{%class_lesson}}')->where(['in', 'class_id', $classManage])->all(Fun::getSiteDb());
        if (empty($query)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($query as $key => $val) {
            $item[$this->getDay($val['class_date'])][] = [
                'lesson_id' => $val['lesson_id'],
                "class_id" => $val['class_id'],
                "class_date" => $this->getDay($val['class_date']),
                "start_time" => $this->getTime($val['start_time']),
                "end_time" => $this->getTime($val['end_time']),
                "lesson" => $val['lesson'],
                "title" => $val['title'],
                "status" => $val['status'],
                "ovo" => $val['ovo'],
                "info" => $val['info']
            ];
            ksort($item);
        }
        foreach ($item as $ik => $iv) {
            $dataArr[] = [
                'time' => $this->getDay($ik),
                'item' => $item[$ik]
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $dataArr,
            'pagination' => [
                'pageSize' => 20
            ],
        ]);
    }


    public function actionEvaluate($lesson_id, $student_id)
    {
        $data = \Yii::$app->request->post();
        $refouceScore = array_key_exists('refouce_score', $data) ? (int)$data['refouce_score'] : '';
        $lessonStudent = (new Query())->select('*')->from('{{%lesson_student}}')
            ->where(['lesson_id' => $lesson_id, 'student_id' => $student_id])
            ->one(Fun::getSiteDb());
        if ($lessonStudent['refouce_score'] != null || ($lessonStudent['refouce_score'] != $refouceScore && $refouceScore != null)) {
            Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                'refouce_score' => $refouceScore
            ], ['lesson_id' => $lesson_id, 'student_id' => $student_id])->execute();
        }
        $evaluateStatus = $data['refouce_score'] == 0 ? 0 : 1;
        return [
            'evaluate_status' => $evaluateStatus,
            'refouce_score' => $data['refouce_score']
        ];
    }

    //pad 教师 一键回复
    public function actionBatchupdate($lesson_id)
    {
        $data = \Yii::$app->request->post();
        $keyReply = array_key_exists('key_reply', $data) ? $data['key_reply'] : '';
        if (!empty($keyReply)) {
            $update = Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                'lesson_fouce' => $keyReply,
            ], 'lesson_id=:lesson_id');
            $update->bindValue(':lesson_id', $lesson_id);
            $update->execute();
        }
        return $data;
    }

    //pad 教师 一键回复课程内容
    public function actionBatchcontent($lesson_id)
    {
        $postData = \Yii::$app->request->post();
        $lessonContent = ArrayHelper::keyExists('lesson_content', $postData) ? $postData['lesson_content'] : '';
        if (!empty($lessonContent)) {
            $update = Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                'lesson_content' => $lessonContent,
            ], 'lesson_id=:lesson_id');
            $update->bindValue(':lesson_id', $lesson_id);
            $update->execute();
        }
        return ['items' => $lessonContent];
    }

    //pad端教师一对多课下练习重点回复
    public function actionReplaypractice()
    {
        $postData = \Yii::$app->request->post();
        $data = Json::decode($postData['array']);
        foreach ($data as $k => $v) {
            $update = Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                'lesson_fouce' => $v['lesson_fouce'],
            ], ['lesson_id' => $v['lesson_id'], 'student_id' => $v['student_id']]);
            $update->execute();
        }
        return ['items' => $data];
    }

    //pad端教师一对多点评
    public function actionComment()
    {
        $postData = \Yii::$app->request->post();
        $data = Json::decode($postData['array']);
        foreach ($data as $k => $v) {
            $update = Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', [
                'lesson_score' => $v['lesson_score'],
            ], ['lesson_id' => $v['lesson_id'], 'student_id' => $v['student_id']]);
            $update->execute();
        }
        return ['items' => $data];
    }

    public function actionMediahit()
    {
        return [
            'items' => '如果当前课程所有学员的课后花絮一样,您可以选择一键上传!(视频限传一个,图片限传四张)'
        ];
    }

    //pad 教师内容 重点等信息填写
    public function actionUpdate($lesson_id, $student_id = '')
    {
        $site_id = Fun::getSiteId();
        $lessonMedia = new LessonMedia();
        $className = get_class($lessonMedia);
        $this->getSiteDb($site_id);
        if (\Yii::$app->request->post() != null) {
            $data = \Yii::$app->request->post();
            $lessonContent = array_key_exists('lesson_content', $data) ? $data['lesson_content'] : '';
            $lessonFouce = array_key_exists('lesson_fouce', $data) ? $data['lesson_fouce'] : '';
            $lessonScore = array_key_exists('lesson_score', $data) ? (int)$data['lesson_score'] : '';
            $refouceAnswer = array_key_exists('refouce_answer', $data) ? $data['refouce_answer'] : '';
            $mType = array_key_exists('m_type', $data) ? (int)$data['m_type'] : '';
            $urlPath = array_key_exists('url_path', $data) ? $data['url_path'] : '';
            $isRefouce = array_key_exists('is_refouce', $data) ? $data['is_refouce'] : '';
            if ($mType != null) {
                $isDefault = 0;
            } else {
                $isDefault = ((int)$mType == 1) ? 0 : 1;
            }
            ArrayHelper::remove($data, 'url_path');
            if (!empty($student_id)) {
                $lessonStudent = (new Query())->select('*')->from('{{%lesson_student}}')
                    ->where(['lesson_id' => $lesson_id, 'student_id' => $student_id])
                    ->one(Fun::getSiteDb());
                if (empty($lessonStudent['lesson_content']) || ($lessonStudent['lesson_content'] != $lessonContent && !empty($lessonContent))) {
                    \Yii::$app->db->createCommand()->update('{{%lesson_student}}', [
                        'lesson_content' => $lessonContent,
                    ], ['lesson_id' => $lesson_id, 'student_id' => $student_id])->execute();
                }
                if (empty($lessonStudent['lesson_fouce']) || ($lessonStudent['lesson_fouce'] != $lessonFouce && !empty($lessonFouce))) {
                    \Yii::$app->db->createCommand()->update('{{%lesson_student}}', [
                        'lesson_fouce' => $lessonFouce,
                    ], ['lesson_id' => $lesson_id, 'student_id' => $student_id])->execute();
                }
                if ($lessonStudent['lesson_score'] != null || ($lessonStudent['lesson_score'] != $lessonScore && $lessonScore != null)) {
                    \Yii::$app->db->createCommand()->update('{{%lesson_student}}', [
                        'lesson_score' => (int)$lessonScore
                    ], ['lesson_id' => $lesson_id, 'student_id' => $student_id])->execute();
                }
                if (empty($lessonStudent['refouce_answer']) || ($lessonStudent['refouce_answer'] != $refouceAnswer && !empty($refouceAnswer))) {
                    $currentData = $this->findModel($lesson_id);
                    $current = ($currentData['lesson'] - 1 == 0) ? $currentData['lesson'] : $currentData['lesson'] - 1;
                    $prevData = (new Query())->select('*')->from('{{%class_lesson}}')->where([
                        'class_id' => $currentData['class_id'],
                        'lesson' => (int)$current,
                        'start_time' => $currentData['start_time'],
                        'end_time' => $currentData['end_time'],
                        'title' => $currentData['title'],
                        'ovo' => $currentData['ovo'],
                    ])->one(Fun::getSiteDb());
                    \Yii::$app->db->createCommand()->update('{{%lesson_student}}', [
                        'refouce_answer' => $refouceAnswer
                    ], ['lesson_id' => (int)$prevData['lesson_id'], 'student_id' => $student_id])->execute();
                }
                $imgArr = $videoArr = [];
                $lessonMedia = (new Query())->select('*')->from('{{%lesson_media}}')
                    ->where(['lesson_id' => $lesson_id, 'student_id' => $student_id, 'm_type' => $mType, 'is_refouce' => 1])->one(Fun::getSiteDb());
                /*foreach ($lessonMedia as $lmv) {
                    if ($lmv['m_type'] == 0) $imgArr[] = $lmv;
                    if ($lmv['m_type'] == 1) $videoArr[] = $lmv;
                }
                if ((int)count($imgArr) > 4 || (int)count($videoArr) > 1) {
                    try {
                        throw new ForbiddenHttpException('媒体资源数目不能超出限制');
                    } catch (ForbiddenHttpException $e) {
                        return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
                    }
                }*/
                $lessonMediaData = [
                    'lesson_id' => $lesson_id, 'student_id' => $student_id, 'm_type' => $mType, 'is_refouce' => 1
                ];
                if (empty($lessonMedia)) {
                    \Yii::$app->db->createCommand()->insert('{{%lesson_media}}', $lessonMediaData)->execute();
                    $objectId = \Yii::$app->db->lastInsertID;
                } else {
                    $objectId = $lessonMedia['id'];
                }
                $insertArr = [
                    'class_name' => $className,
                    'object_id' => $objectId,
                    'alt' => '移动端成长日志',
                    'created_at' => time(),
                    'is_default' => $isDefault,
                    'file_path' => $urlPath
                ];
                \Yii::$app->db->createCommand()->insert('{{%medias}}', $insertArr)->execute();
                return ['items' => ArrayHelper::merge($insertArr, $lessonMediaData, $data)];
            }
            $classStudent = (new Query())->select('cs.student_id')->from('{{%class_lesson}} cl')
                ->leftJoin('{{%class_student}} cs', 'cl.class_id=cs.class_manage_id')
                ->where(['cl.lesson_id' => $lesson_id])
                ->all(Fun::getSiteDb());
            $returnArr = [];
            $lessonMediaArr = $studentIdArr = [];
            foreach ($classStudent as $key => $val) {
                $lessonMediaData = [
                    'lesson_id' => $lesson_id,
                    'student_id' => $val['student_id'],
                    'm_type' => $mType,
                    'is_refouce' => 1,
                ];
                $lessonMedia = (new Query())->select('*')->from('{{%lesson_media}}')
                    ->where(['lesson_id' => $lesson_id, 'student_id' => $val['student_id'], 'm_type' => $mType, 'is_refouce' => 1])
                    ->one(Fun::getSiteDb());
                if (empty($lessonMedia)) {
                    \Yii::$app->db->createCommand()->insert('{{%lesson_media}}', $lessonMediaData)->execute();
                    $objectId = \Yii::$app->db->lastInsertID;
                } else {
                    $objectId = $lessonMedia['id'];
                }
                $insertArr = [
                    'class_name' => $className,
                    'object_id' => $objectId,
                    'alt' => '移动端成长日志',
                    'created_at' => time(),
                    'is_default' => $isDefault,
                    'file_path' => $urlPath
                ];
                \Yii::$app->db->createCommand()->insert('{{%medias}}', $insertArr)->execute();
                $returnArr[] = ArrayHelper::merge($lessonMediaData, $insertArr);
                $lessonMediaArr[] = (new Query())->select('*')->from('{{%lesson_media}}')
                    ->where(['lesson_id' => $lesson_id, 'student_id' => $val['student_id']])->all(Fun::getSiteDb());
            }
            return ['items' => $returnArr];
        }
    }

//教师成长日志按照班级管理
    public function actionFindbyteache($teache_id)
    {
        $data = $classStudentArr = $classManageId = $arr = [];
        $teacher = (new Query())->select('*')->from('{{%admin}}')
            ->where(['id' => $teache_id, 'role' => 'teache_teacher'])->one(Fun::getSiteDb());
        //$arrangeCourse = ArrangeCourse::find()->where(['teacher_id' => $teacher['teacher_id']])->all();
        $arrangement = Arrangement::find()->where(['teacher_id' => $teacher['teacher_id']])->all();
        $classManage = ClassManage::find()->where(['is_old' => 1])->all();
        foreach ($classManage as $ck => $cv) {
            $classManageId[] = $cv->class_id;
        }
        $classStudent = ClassStudent::find()
            ->where(['in', 'class_manage_id', $classManageId])->asArray()->all();
        foreach ($classStudent as $sk => $sv) {
            $classStudentArr[$sv['class_manage_id']][] = $sv;
        }
        if (empty($arrangement)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($arrangement as $k => $v) {
            foreach ($classManage as $key => $val) {
                if ($val->associate_id == $v->id) {
                    $data['items'][] = [
                        'class_id' => $val->class_id,
                        'course_name' => isset($v->course) ? $v->course->name : '',
                        'course_img' => isset($v->teacher) ? $v->teacher->img : '',
                        'student_num' => isset($classStudentArr[$val['class_id']]) ? count($classStudentArr[$val['class_id']]) : 0,
                        'attendance_rate' => '90%',
                        'already_lesson' => $this->getAlreadyLesson($val)['already_lesson'],
                        'ovo' => empty($this->getAlreadyLesson($val)['ovo']) ? 0 : $this->getAlreadyLesson($val)['ovo'],
                        'course_status' => 0
                    ];
                }
            }
        }

        return $data;
    }


    public function actionFindbytcid($class_id)
    {
        $data = [];
        $customer = Customer::find()->where(['site_id' => Fun::getSiteId()])->asArray()->all();
        $class_student = (new Query())->select('*')->from('{{%student}} a')
            ->leftJoin('{{%class_student}} b', 'b.student_id=a.id')
            ->where(['b.class_manage_id' => $class_id])
            ->all(Fun::getSiteDb());
        foreach ($customer as $k => $v) {
            foreach ($class_student as $kk => $vv) {
                if ($v['id'] = $vv['customer_id']) {
                    $data['items'][$vv['id']] = [
                        'student_id' => $vv['student_id'],
                        'student_name' => $vv['name'],
                        'student_img' => $vv['img'],
                        'age' => $vv['age'],
                        'attendance_rate' => '90%',
                        'already_lesson' => ClassLesson::find()->where(['class_id' => $class_id, 'status' => 1])->count() .
                            '/' . ClassLesson::find()->where(['class_id' => $class_id])->count(),
                        'tel' => $v['tel']
                    ];
                }
            }
        }
        return $data;
    }

    public function actionGettime($class_id)
    {
        $timeArr = [];
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id, 'status' => 0])->limit(5)->all(Fun::getSiteDb());
        foreach ($classLesson as $k => $v) {
            $timeArr[] = [
                'timestamp' => $v['class_date'],
                'time' => \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd')
            ];
        }
        return ['items' => $timeArr];
    }

//pad 教师 延课
    public function actionDelay($class_id, $time)
    {
        $alreadyTimeArr = $remainTimeArr = $lessonArr = [];
        $lessonStatus = '';
        $this->getSiteDb(Fun::getSiteId());
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])
            ->all();
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonArr = $v;
                $lessonStatus = $v['status'];
            }
            if ($v['status'] == 1) {
                $alreadyArr[] = $v;
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] != 1) {
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] == 0) {
                $classTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
                $classArr[] = $v;
            }
        }
        if (in_array($time, $alreadyTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if ($lessonStatus == 2) {
            try {
                throw new ForbiddenHttpException('您选的该课程已被延课');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if ($lessonStatus != 0) {
            try {
                throw new ForbiddenHttpException('您选的该课程不能被延课，请正确选择课程');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $year = substr($time, 0, 4);
        $monthData = substr($time, stripos($time, '-') + 1, 2);
        $month = strstr($time, '-') ? substr($monthData, 0, 1) : substr($monthData, 0, 2);
        $day = substr($time, strripos($time, '-') + 1);
        $data['items'] = [
            'time' => $time,
            'info' => '您当前选择的请假日期为' . $year . '年' . $month . '月' . $day . '日,为该课程的第' . $lessonArr['lesson'] . '节课'
        ];
        return $data;
    }

    public function actionDelayclass($class_id, $time, $teache_id)
    {
        $lessonId = '';
        $this->getSiteDb(Fun::getSiteId());
        $alreadyArr = $remainArr = $alreadyTimeArr = $classTimeArr = $classArr = $remainTimeArr = [];
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])
            ->all();
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonId = $v['lesson_id'];
            }
            if ($v['status'] == 1) {
                $alreadyArr[] = $v;
            }
            if ($v['status'] != 1) {
                $remainArr[] = $v;
            }
        }
        $classLessonArr = ['teache_id' => $teache_id, 'remark' => '教师延课', 'status' => 2];
        \Yii::$app->db->createCommand()->update(
            '{{%class_lesson}}', ['status' => 2, 'info' => serialize($classLessonArr)], ['lesson_id' => $lessonId]
        )->execute();
        $classLesson = (new Query())->select('*')
            ->from('{{%class_lesson}}')
            ->where(['lesson_id' => $lessonId])
            ->one();
        $allLesson = (int)count($alreadyArr) + (int)count($remainArr);
        $currentLesson = $classLesson['lesson'];
        $currentDay = $classLesson['class_date'];
        $lastDay = (int)$currentDay + ((int)$allLesson - (int)$currentLesson + 1) * 7 * 24 * 60 * 60;
        $startTime = $classLesson['start_time'];
        $insertArr = [
            'class_id' => (int)$classLesson['class_id'],
            'class_date' => (int)$lastDay,
            'start_time' => (int)$startTime,
            'end_time' => (int)$classLesson['end_time'],
            'lesson' => $allLesson + 1,
            'title' => $classLesson['title'],
            'status' => 0,
            'ovo' => (int)$classLesson['ovo'],
        ];
        \Yii::$app->db->createCommand()->insert('{{%class_lesson}}', $insertArr)->execute();
        return ['items' => $this->findModel($lessonId)];
    }

//pad端教师代课
    public function actionReplace($class_id, $time)
    {
        $alreadyTimeArr = $remainTimeArr = $lessonArr = [];
        $lessonStatus = '';
        $this->getSiteDb(Fun::getSiteId());
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->all();
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonArr = $v;
                $lessonStatus = $v['status'];
            }
            if ($v['status'] == 1) {
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
                $alreadyArr[] = $v;
            }
            if ($v['status'] != 1) {
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
        }
        if (in_array($time, $alreadyTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if ($lessonStatus == 5) {
            try {
                throw new ForbiddenHttpException('您选的该课程已被代课');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if ($lessonStatus != 0) {
            try {
                throw new ForbiddenHttpException('您选的该课程不能被代课，请正确选择课程');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $year = substr($time, 0, 4);
        $monthData = substr($time, stripos($time, '-') + 1, 2);
        $month = strstr($time, '-') ? substr($monthData, 0, 1) : substr($monthData, 0, 2);
        $day = substr($time, strripos($time, '-') + 1);
        $data['items'] = [
            'time' => $time,
            'info' => '您当前选择的代课日期为' . $year . '年' . $month . '月' . $day . '日,为该课程的第' . $lessonArr['lesson'] . '节课'
        ];
        return $data;
    }

    public function actionReplaceclass($class_id, $time, $teache_id)
    {
        $lessonId = '';
        $this->getSiteDb(Fun::getSiteId());
        $data = \Yii::$app->request->post();
        $teacherName = ArrayHelper::keyExists('teacher_name', $data) ? $data['teacher_name'] : '';
        $teacherTel = ArrayHelper::keyExists('teacher_tel', $data) ? $data['teacher_tel'] : '';
        $remark = ArrayHelper::keyExists('remark', $data) ? $data['remark'] : '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->all();
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonId = $v['lesson_id'];
            }
        }
        $replace = [
            'teache_id' => $teache_id, 'teacher_name' => $teacherName, 'teacher_tel' => $teacherTel, 'remark' => $remark, 'status' => 5
        ];
        \Yii::$app->db->createCommand()->update('{{%class_lesson}}', [
            'info' => serialize($replace), 'status' => 5
        ], ['lesson_id' => $lessonId])->execute();
        return $this->findModel($lessonId);
    }

//停课原因
    public function actionStopreason()
    {
        $data['items'] = [
            '学生返校', '身体不适', '自然灾害', '外出旅游'
        ];
        return $data;
    }

    public function actionStop($class_id, $teache_id)
    {
        $data['items'] = [
            'info' => '提示:当前课程将会停止,需要满足在规定停课条件的前提下,提前1天申请,是否确定停课'
        ];
        return $data;
    }

//教师停课
    public function actionStopclass($class_id, $teache_id)
    {
        $this->getSiteDb(Fun::getSiteId());
        $postData = \Yii::$app->request->post();
        $reason = ArrayHelper::keyExists('reason', $postData) ? $postData['reason'] : '';
        $remark = ArrayHelper::keyExists('remark', $postData) ? $postData['remark'] : '';
        $lessonId = '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->all();
        foreach ($classLesson as $k => $v) {
            if ($v['status'] == 0) {
                $lessonId [] = $v['lesson_id'];
            }
        }
        $stop = ['teache_id' => $teache_id, 'reason' => $reason, 'remark' => $remark, 'status' => 4];
        \Yii::$app->db->createCommand()->update('{{%class_lesson}}', ['status' => 4, 'info' => serialize($stop)], ['in', 'lesson_id', $lessonId])->execute();
        $data['items'] = ['status' => 4, 'info' => '停课成功'];
        return $data;
    }

//教师复课
    public function actionRecover($class_id, $time)
    {
        $lessonArr = [];
        $this->getSiteDb(Fun::getSiteId());
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->all();
        foreach ($classLesson as $k => $v) {
            if ($v['status'] == 4) {
                $lessonArr[] = $v;
            }
        }
        if (empty($lessonArr)) {
            try {
                throw new NotFoundHttpException('当前没有可恢复课程');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $year = substr($time, 0, 4);
        $monthData = substr($time, stripos($time, '-') + 1, 2);
        $month = strstr($time, '-') ? substr($monthData, 0, 1) : substr($monthData, 0, 2);
        $day = substr($time, strripos($time, '-') + 1);
        $data['items'] = [
            'time' => $time,
            'info' => '您当前选择的代课日期为' . $year . '年' . $month . '月' . $day . '日,为该课程的第' . $lessonArr[0]['lesson'] . '节课'
        ];
        return $data;
    }

    public function actionRecoverclass($class_id, $time, $teache_id)
    {
        $lessonIdArr = [];
        $this->getSiteDb(Fun::getSiteId());
        $lessonId = (new Query())->select('lesson_id')->from('{{%class_lesson}}')->where(['class_id' => $class_id, 'status' => 4])->column();
        if (empty($lessonId)) {
            try {
                throw new NotFoundHttpException('您当前没有处在停课状态的课程');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $recover = ['teache_id' => $teache_id, 'remark' => '教师复课', 'status' => 6];
        foreach ($lessonId as $k => $v) {
            $lessonIdArr[$k + 1] = $v;
        }
        foreach ($lessonIdArr as $kk => $vv) {
            for ($i = 1; $i <= count($lessonId); $i++) {
                if ($i == $kk) {
                    $insertArr[$i]['class_date'] = \Yii::$app->formatter->asTimestamp($time) + ($i - 1) * 7 * 24 * 60 * 60;
                    $insertArr[$i]['lesson_id'] = $vv;
                    \Yii::$app->db->createCommand()->update('{{%class_lesson}}', [
                        'class_date' => $insertArr[$i]['class_date'], 'status' => 6, 'info' => serialize($recover)
                    ], ['lesson_id' => $insertArr[$i]['lesson_id']])->execute();
                }
            }
        }
        $data['items'] = ['status' => 6, 'info' => '申请复课成功'];
        return $data;
    }

//班主任教学日志
    public function actionFindbyheadmaster($teacher_id)
    {
        $dataArr = $time = $item = [];
        $admin = (new Query())->select('*')->from('{{%admin}}')->where(['id' => $teacher_id])->one(Fun::getSiteDb());
        if (empty($admin['teacher_id'])) {
            try {
                throw new ForbiddenHttpException('您不是教师不能查看该功能');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $arrangeCourse = (new Query())->select('id')->from('{{%arrange_course}}')
            ->where(['teacher_id' => $admin['teacher_id']])
            ->column(Fun::getSiteDb());
        $classManage = (new Query())->select('class_id')->from('{{%class_manage}}')
            ->where(['in', 'code', $arrangeCourse])
            ->column(Fun::getSiteDb());
        $query = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['in', 'class_id', $classManage])
            ->all(Fun::getSiteDb());
        if (empty($query)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($query as $key => $val) {
            $item[$this->getDay($val['class_date'])][] = [
                'lesson_id' => $val['lesson_id'],
                "class_id" => $val['class_id'],
                "class_date" => $this->getDay($val['class_date']),
                "start_time" => $this->getTime($val['start_time']),
                "end_time" => $this->getTime($val['end_time']),
                "lesson" => $val['lesson'],
                "title" => $val['title'],
                "status" => $val['status'],
                "ovo" => $val['ovo'],
                "info" => $val['info']
            ];
            ksort($item);
        }
        foreach ($item as $ik => $iv) {
            $dataArr[] = [
                'time' => $this->getDay($ik),
                'item' => $item[$ik]
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $dataArr,
            'pagination' => [
                'pageSize' => 20
            ],
        ]);
    }


//班主任根据课程名字
    public function actionFindbytc($teacher_id, $class_name)
    {
        $dataArr = [];
        $course_data = Course::find()->where(['name' => $class_name, 'site_id' => Fun::getSiteId()])->one();
        $data = ClassManage::find()->where(['headmaster' => $teacher_id])->all();
        if (empty($data)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($data as $k => $v) {
            $dataArr['items'][] = [
                "class_id" => $v->class_id,
                "class_code" => $v->class_code,
                "headmaster" => $v->headmaster,
                "code" => $v->code,
                "status" => $v->status,
                "start_time" => \Yii::$app->formatter->asDatetime($v->start_time, 'yyyy-MM-dd h:i:s'),
                "end_time" => \Yii::$app->formatter->asDatetime($v->end_time, 'yyyy-MM-dd h:i:s'),
                "pclass_id" => $v->pclass_id
            ];
        }
        return $dataArr;
    }

//班主任按课程管理
    public function actionCategory()
    {
        $data = [];
        $query = Category::find()->where(['parent_id' => 0])->all();
        foreach ($query as $k => $v) {
            $data['item'][] = [
                'id' => $v->id,
                'name' => $v->name,
                'wechat_image' => $v->wechat_image
            ];
        }
        return $data;
    }

    public function actionFindbyteacher($teacher_id)
    {
        $siteId = Fun::getSiteId();
        $data = [];
        $classManage = ClassManage::find()->with('arrangeMent')->where(['headmaster' => $teacher_id])->all();
        //var_dump($classManage);exit();
        if (empty($classManage)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($classManage as $k => $v) {
            switch ($v->is_old) {
                case 0://关联商品id
                    $goods = (new Query())->select('*')->from('{{%goods}}')
                        ->where(['id' => $v['associate_id']])
                        ->one($this->getDb($siteId));
                    $goodsAttr = (new Query())->select('*')->from('{{%goods_attr}}')
                        ->where(['goods_id' => $goods['id'], 'obj_type' => 'teacher'])
                        ->indexBy('obj_type')
                        ->all($this->getDb($siteId));
                    if (empty($goods) || empty($goodsAttr)) {
                        try {
                            throw new NotFoundHttpException('信息不存在');
                        } catch (NotFoundHttpException $e) {
                            return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
                        }
                    }
                    $teacher = (new Query())->select('*')->from('{{%teacher}}')
                        ->where(['id' => $goodsAttr['teacher']['attribute_id']])
                        ->one($this->getDb($siteId));
                    //var_dump($teacher);exit();
                    $data['items'][] = [
                        'class_id' => $v->class_id,
                        'course_img' => $teacher['img'],
                        'course_name' => 'test',//课程名称
                        'teacher_name' => $teacher['name'],//教师名称
                        /*'student_num' => ClassStudent::find()->where(['class_manage_id' => $v->class_id])->count(),//学生数量
                        'attendance_rate' => '90%',//出勤率
                        'already_lesson' => ClassLesson::find()->where(['class_id' => $v->class_id, 'status' => 1])->count() .
                            '/' . ClassLesson::find()->where(['class_id' => $v->class_id])->count(),*/
                        'student_num' => '36',//学生数量
                        'attendance_rate' => '90%',//出勤率
                        'already_lesson' => '6/12',
                    ];
                    break;
                case 1://关联排课id
                    $teacher = (new Query())->select(['t.name as name', 't.img as img', 'c.name as title'])->from('{{%arrangement}} a')
                        ->leftJoin('{{%teacher}} t', 'a.teacher_id=t.id')
                        ->leftJoin('{{%course}} c', 'a.course_id=c.id')
                        ->where(['a.id' => $v['associate_id']])
                        ->one($this->getDb($siteId));
                    $data['items'][] = [
                        'class_id' => $v->class_id,
                        'course_img' => $teacher['img'],
                        'course_name' => $teacher['title'],//课程名称
                        'teacher_name' => $teacher['name'],//教师名称
                        /*'student_num' => ClassStudent::find()->where(['class_manage_id' => $v->class_id])->count(),//学生数量
                        'attendance_rate' => '90%',//出勤率
                        'already_lesson' => ClassLesson::find()->where(['class_id' => $v->class_id, 'status' => 1])->count() .
                            '/' . ClassLesson::find()->where(['class_id' => $v->class_id])->count(),*/
                        'student_num' => '36',//学生数量
                        'attendance_rate' => '90%',//出勤率
                        'already_lesson' => '6/12',
                    ];
                    break;
            }
        }
        return $data;
    }

    public function actionFindbycategory($teacher_id, $category_id)
    {
        $data = [];
        $classManage = ClassManage::find()->with('arrangeMent')->where(['headmaster' => $teacher_id])->all();
        $category = Cate::find()->where(['id' => $category_id])->orderBy('id ASC')->one();
        $childArr = explode(',', $category->arrchildid);
        foreach ($classManage as $k => $v) {
            if (in_array($v->arrangeMent->course->category_id, $childArr)) {
                $data['items'][] = [
                    'class_id' => $v->class_id,
                    'course_img' => $v->arrangeMent->teacher->img,
                    'course_name' => $v->arrangeMent->course->name,//课程名称
                    'teacher_name' => $v->arrangeMent->teacher->name,//教师名称
                    /*'student_num' => ClassStudent::find()->where(['class_manage_id' => $v->class_id])->count(),//学生数量
                        'attendance_rate' => '90%',//出勤率
                        'already_lesson' => ClassLesson::find()->where(['class_id' => $v->class_id, 'status' => 1])->count() .
                            '/' . ClassLesson::find()->where(['class_id' => $v->class_id])->count(),*/
                    'student_num' => '36',//学生数量
                    'attendance_rate' => '90%',//出勤率
                    'already_lesson' => '6/12',
                ];
            }

        }
        if (empty($data)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        return $data;
    }

//班主任成长日志按学生管理
    public function actionFindbystudent($teacher_id)
    {
        $data = [];
        $studentId = (new Query())->select('student_id')->from('{{%class_student}} a')
            ->leftJoin('{{%class_manage}} b', 'b.class_id=a.class_manage_id')
            ->where(['b.headmaster' => $teacher_id])
            ->groupBy('a.student_id')->column(Fun::getSiteDb());
        $studentData = (new Query())->select('*')->from('{{%student}}')->where(['in', 'id', $studentId])->all(Fun::getSiteDb());
        if (empty($studentData)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($studentData as $k => $v) {
            $data[] = [
                'student_id' => $v['id'],
                'student_name' => $v['name'],
                'age' => $v['age'],
                'tel' => $this->getTel($v['customer_id']),
                'course_list' => $this->getCourseList($v['id'])
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20
            ],
            'sort' => [
                'attributes' => ['id']
            ]
        ]);
    }


    public function actionFindbyname($teacher_id, $name = null)
    {
        $data = [];
        $studentId = (new Query())->select('student_id')->from('{{%class_student}} a')
            ->leftJoin('{{%class_manage}} b', 'b.class_id=a.class_manage_id')
            ->where(['b.headmaster' => $teacher_id])->groupBy('a.student_id')
            ->column(Fun::getSiteDb());
        $studentModel = (new Query())->select('*')->from('{{%student}}')->where(['in', 'id', $studentId]);
        if (!empty($name)) {
            $studentModel->andWhere(['name' => $name]);
        }
        $studentData = $studentModel->all(Fun::getSiteDb());
        if (empty($studentData)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($studentData as $k => $v) {
            $data[] = [
                'student_id' => $v['id'],
                'student_name' => $v['name'],
                'student_img' => $v['img'],
                'age' => $v['age'],
                'tel' => $this->getTel($v['customer_id']),
                'course_list' => $this->getCourseList($v['id'])
            ];
        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20
            ],
        ]);

    }


//班主任延课
    public function actionHeadmasterdelay($class_id, $time)
    {
        $lessonId = $courseStartTime = '';
        $alreadyArr = $remainArr = $alreadyTimeArr = $classTimeArr = $classArr = $remainTimeArr = [];
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])->all(Fun::getSiteDb());
        $lessonStatus = '';
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonStatus = $v['status'];
                $lessonId = $v['lesson_id'];
                $courseStartTime = Util::getTime($v['start_time']);
            }
            if ($v['status'] == 1) {
                $alreadyArr[] = $v;
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] != 1) {
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] == 0) {
                $classTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
                $classArr[] = $v;
            }
        }
        if ($lessonStatus != 0) {
            try {
                throw new ForbiddenHttpException('该课程不能被延课');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (in_array($time, $alreadyTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $teach = (new Query())->select('*')->from('{{%class_manage}} c')
            ->leftJoin('{{%arrange_course}} a', 'c.code=a.id')
            ->where(['c.class_id' => $class_id])
            ->one(Fun::getSiteDb());
        $classLessonArr = ['teache_id' => $teach['teacher_id'], 'remark' => '班主任延课', 'status' => 2];
        \Yii::$app->db->createCommand()
            ->update('{{%class_lesson}}', ['status' => 2, 'info' => serialize($classLessonArr)], ['lesson_id' => $lessonId])->execute();
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['lesson_id' => $lessonId])->one(Fun::getSiteDb());
        $allLesson = (int)count($alreadyArr) + (int)count($remainArr);
        $currentLesson = $classLesson['lesson'];
        $currentDay = $classLesson['class_date'];
        $lastDay = (int)$currentDay + ((int)$allLesson - (int)$currentLesson + 1) * 7 * 24 * 60 * 60;
        $startTime = $classLesson['start_time'];
        $insertArr = [
            'class_id' => (int)$classLesson['class_id'],
            'class_date' => (int)$lastDay,
            'start_time' => (int)$startTime,
            'end_time' => (int)$classLesson['end_time'],
            'lesson' => $allLesson + 1,
            'title' => $classLesson['title'],
            'status' => 0,
            'ovo' => (int)$classLesson['ovo'],
        ];
        \Yii::$app->db->createCommand()->insert('{{%class_lesson}}', $insertArr)->execute();
        $class_student = (new Query())->select([
            'cl.class_id as class_id', 'a.customer_id as customer_id', 'a.id as student_id', 'a.name as student_name', 'a.img as student_img',
            'a.age as age', 'cl.ovo as ovo'])
            ->from('{{%student}} a')
            ->leftJoin('{{%class_student}} b', 'b.student_id=a.id')
            ->leftJoin('{{%class_lesson}} cl', 'b.class_manage_id=cl.class_id')
            ->where(['b.class_manage_id' => $class_id])
            ->groupBy(['b.class_manage_id', 'b.student_id'])
            ->all(Fun::getSiteDb());
        $data = [];
        $courseTime = $time . ' ' . $courseStartTime;
        $subtractTime = strtotime($courseTime) - (int)time();
        $subtractDay = (int)($subtractTime / (3600 * 24));
        $subtractHour = (int)(($subtractTime % (3600 * 24)) / (3600));
        $subtractMin = (int)($subtractTime % (3600) / 60);
        $data['items']['time'] = $time;
        foreach ($class_student as $kk => $vv) {
            $data['items']['student_list'][] = [
                'class_id' => $class_id,
                'student_id' => $vv['student_id'],
                'student_name' => $vv['student_name'],
                'student_img' => $vv['student_img'],
                'age' => $vv['age'],
                'attendance_rate' => '90%',
                'already_lesson' => ClassLesson::find()->where(['class_id' => $class_id, 'status' => 1])->count() .
                    '/' . ClassLesson::find()->where(['class_id' => $class_id])->count(),
                'tel' => $this->getTel($vv['customer_id']),
                'status' => $vv['ovo'],
                'agree_status' => $this->getAgreeStatus($vv['student_id'])
            ];
        }
        $disagreeArr = [];
        foreach ($data['items']['student_list'] as $key => $val) {
            if ($val['agree_status'] == 0) {
                $disagreeArr[] = $val;
            }
        }

        $data['items']['hit'] = '距离本次开课时间还有' . $subtractDay . '天' . $subtractHour . '小时' .
            $subtractMin . '分,' . '还有' . count($disagreeArr) . '位家长没同意';

        return $data;
    }

//班主任代课
    public function actionHeadmasterreplace($class_id, $time)
    {
        $lessonId = [];
        //$this->getSiteDb(Fun::getSiteId());
        $data = \Yii::$app->request->post();
        $alreadyArr = $remainArr = $alreadyTimeArr = $remainTimeArr = [];
        $teacherName = ArrayHelper::keyExists('teacher_name', $data) ? $data['teacher_name'] : '';
        $teacherTel = ArrayHelper::keyExists('teacher_tel', $data) ? $data['teacher_tel'] : '';
        $remark = ArrayHelper::keyExists('remark', $data) ? $data['remark'] : '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])->all(Fun::getSiteDb());
        $courseStartTime = $lessonStatus = '';
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d')) {
                $lessonId = $v['lesson_id'];
                $lessonStatus = $v['status'];
                $courseStartTime = Util::getTime($v['start_time']);
            }
            if ($v['status'] == 1) {
                $alreadyArr[] = $v;
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] != 1) {
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
            }
            if ($v['status'] == 0) {
                $classTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-M-d');
                $classArr[] = $v;
            }
        }
        if ($lessonStatus != 0) {
            try {
                throw new ForbiddenHttpException('该课程不能被代课');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (in_array($time, $alreadyTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能代课,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能代课,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $teach = (new Query())->select('*')->from('{{%class_manage}} c')
            ->leftJoin('{{%arrange_course}} a', 'c.code=a.id')
            ->where(['c.class_id' => $class_id])
            ->one(Fun::getSiteDb());
        $replace = [
            'teache_id' => $teach['teacher_id'], 'teacher_name' => $teacherName, 'teacher_tel' => $teacherTel, 'remark' => $remark, 'status' => 5
        ];
        \Yii::$app->db->createCommand()->update('{{%class_lesson}}', [
            'info' => serialize($replace), 'status' => 5
        ], ['lesson_id' => $lessonId])->execute();
        $class_student = (new Query())->select([
            'cl.class_id as class_id', 'a.customer_id as customer_id', 'a.id as student_id', 'a.name as student_name', 'a.img as student_img',
            'a.age as age', 'cl.ovo as ovo'])
            ->from('{{%student}} a')
            ->leftJoin('{{%class_student}} b', 'b.student_id=a.id')
            ->leftJoin('{{%class_lesson}} cl', 'b.class_manage_id=cl.class_id')
            ->where(['b.class_manage_id' => $class_id])
            ->groupBy(['b.class_manage_id', 'b.student_id'])
            ->all(Fun::getSiteDb());
        $data = [];
        $courseTime = $time . ' ' . $courseStartTime;
        $subtractTime = strtotime($courseTime) - (int)time();
        $subtractDay = (int)($subtractTime / (3600 * 24));
        $subtractHour = (int)(($subtractTime % (3600 * 24)) / (3600));
        $subtractMin = (int)($subtractTime % (3600) / 60);
        $data['items']['time'] = $time;
        foreach ($class_student as $kk => $vv) {
            $data['items']['student_list'][] = [
                'class_id' => $class_id,
                'student_id' => $vv['student_id'],
                'student_name' => $vv['student_name'],
                'student_img' => $vv['student_img'],
                'age' => $vv['age'],
                'attendance_rate' => '90%',
                'already_lesson' => ClassLesson::find()->where(['class_id' => $class_id, 'status' => 1])->count() .
                    '/' . ClassLesson::find()->where(['class_id' => $class_id])->count(),
                'tel' => $this->getTel($vv['customer_id']),
                'status' => $vv['ovo'],
                'agree_status' => $this->getAgreeStatus($vv['student_id'])
            ];
        }
        $disagreeArr = [];
        foreach ($data['items']['student_list'] as $key => $val) {
            if ($val['agree_status'] == 0) {
                $disagreeArr[] = $val;
            }
        }

        $data['items']['hit'] = '距离本次开课时间还有' . $subtractDay . '天' . $subtractHour . '小时' .
            $subtractMin . '分,' . '还有' . count($disagreeArr) . '位家长没同意';
        return $data;
    }

//班主任一键清除状态
    public function actionClear($class_id)
    {
        $data = [];
        $class_student = (new Query())->select([
            'cl.class_id as class_id', 'a.customer_id as customer_id', 'a.id as student_id', 'a.name as student_name', 'a.img as student_img',
            'a.age as age', 'cl.ovo as ovo', 'cl.lesson_id as lesson_id', 'cl.class_date as class_date'])
            ->from('{{%student}} a')
            ->leftJoin('{{%class_student}} b', 'b.student_id=a.id')
            ->leftJoin('{{%class_lesson}} cl', 'b.class_manage_id=cl.class_id')
            ->where(['b.class_manage_id' => $class_id])
            ->groupBy(['b.class_manage_id', 'b.student_id'])
            ->all(Fun::getSiteDb());
        foreach ($class_student as $kk => $vv) {
            $data['items']['student_list'][] = [
                'class_id' => $class_id,
                'student_id' => $vv['student_id'],
                'student_name' => $vv['student_name'],
                'student_img' => $vv['student_img'],
                'age' => $vv['age'],
                'attendance_rate' => '90%',
                'already_lesson' => ClassLesson::find()->where(['class_id' => $class_id, 'status' => 1])->count() .
                    '/' . ClassLesson::find()->where(['class_id' => $class_id])->count(),
                'tel' => $this->getTel($vv['customer_id']),
                'status' => $vv['ovo'],
                'agree_status' => '0'
            ];
        }
        $class_lesson = (new Query())->select('lesson_id')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id, 'status' => 0])->orderBy('lesson_id')->column(Fun::getSiteDb());
        if (empty($class_lesson)) {
            try {
                throw new NotFoundHttpException('信息错误');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $lessonId = $class_lesson[0];
        \Yii::$app->db->createCommand()->update('{{%class_lesson}}', [
            'info' => '', 'status' => 0
        ], ['lesson_id' => $lessonId])->execute();
        $data['items']['hit'] = '';
        return $data;
    }


//本主任根据课程显示相应的学生列表
    public function actionFindbycid($class_id)
    {
        $data = [];
        $classManage = ClassManage::find()->where(['class_id' => $class_id])->all();
        $class_student = (new Query())->select([
            'cl.class_id as class_id', 'a.customer_id as customer_id', 'a.id as student_id', 'a.name as student_name', 'a.img as student_img',
            'a.age as age', 'cl.ovo as ovo'])
            ->from('{{%student}} a')
            ->leftJoin('{{%class_student}} b', 'b.student_id=a.id')
            ->leftJoin('{{%class_lesson}} cl', 'b.class_manage_id=cl.class_id')
            ->where(['b.class_manage_id' => $class_id])
            ->groupBy(['b.class_manage_id', 'b.student_id'])
            ->all(Fun::getSiteDb());
        if (empty($class_student)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($class_student as $kk => $vv) {
            $data['items']['student_list'][] = [
                'class_id' => $class_id,
                'student_id' => $vv['student_id'],
                'student_name' => $vv['student_name'],
                'student_img' => $vv['student_img'],
                'age' => $vv['age'],
                'attendance_rate' => '90%',
                'already_lesson' => ClassLesson::find()->where(['class_id' => $class_id, 'status' => 1])->count() .
                    '/' . ClassLesson::find()->where(['class_id' => $class_id])->count(),
                'tel' => $this->getTel($vv['customer_id']),
                'status' => $vv['ovo'],
                'agree_status' => '0'
            ];
        }
        $data['items']['hit'] = '';
        return $data;
    }

    protected function getAgreeStatus($student_id)
    {
        if (in_array($student_id, [361, 363, 431, 440, 474])) {
            return '1';
        }
        return '0';
    }

//  班主任课程详情

    public function actionFindbystu($class_id, $student_id)
    {
        $data = [];
        $classLesson = (new Query())->select(['ls.student_id as student_id', 'os.title as title', 'cl.lesson as lesson', 'cl.class_date as class_date',
            't.name as name', 't.img as img', 'ls.refouce_answer as refouce_answer', 'ls.lesson_score as lesson_score',
            'ls.lesson_content as lesson_content', 'ls.lesson_fouce as lesson_fouce', 'ls.refouce_score as refouce_score',
            'cl.lesson_id as lesson_id', 'cl.ovo as ovo', 'ls.refouce_notice as refouce_notice'])
            ->from('{{%class_student}} cs')
            ->leftJoin('{{%class_lesson}} cl', 'cs.class_manage_id=cl.class_id')
            ->leftJoin('{{%order_sales}} os', 'cs.order_sales_id=os.id')
            ->leftJoin('{{%lesson_student}} ls', 'cl.lesson_id=ls.lesson_id')
            ->leftJoin('{{%teacher}} t', 'os.teacher_id=t.id')
            ->where(['cs.class_manage_id' => $class_id, 'cs.student_id' => $student_id, 'ls.student_id' => $student_id])
            ->all(Fun::getSiteDb());
        if (empty($classLesson)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($classLesson as $k => $v) {
            if ($v['ovo'] == 0) {
                $data[] = [
                    'student_id' => $student_id,
                    'course_name' => $v['title'],//课程名称
                    'class_lesson' => $v['lesson'],//课次
                    'course_time' => \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd'),//时间
                    'teacher_name' => $v['name'],//教师姓名
                    'teacher_img' => $v['img'],//教师头像
                    'refouce_notice' => $v['refouce_notice'],
                    'refouce_answer' => $v['refouce_answer'],//回复
                    'lesson_score_status' => $v['lesson_score'],
                    'lesson_score' => $this->getLessonScore($v['lesson_score']),//评价
                    'lesson_content' => $v['lesson_content'],//上课内容
                    'lesson_fouce' => $v['lesson_fouce'],//课下重点
                    'refouce_score' => $v['refouce_score'],//练习评分
                    'credits' => $this->getCredits($v['lesson_id'], $student_id)
                ];
            } else {
                $data[] = [
                    'student_id' => $student_id,
                    'course_name' => $v['title'],//课程名称
                    'class_lesson' => $v['lesson'],//课次
                    'course_time' => \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd'),//时间
                    'teacher_name' => $v['name'],//教师姓名
                    'teacher_img' => $v['img'],//教师头像
                    'refouce_notice' => $v['refouce_notice'],
                    'refouce_answer' => $v['refouce_answer'],//回复
                    'lesson_score_status' => $v['lesson_score'],
                    'lesson_score' => $this->getLessonScore($v['lesson_score']),//评价
                    'lesson_content' => $v['lesson_content'],//上课内容
                    'lesson_fouce' => $v['lesson_fouce'],//课下重点
                    'refouce_score' => $v['refouce_score'],//练习评分
                    'credits' => $this->getCredits($v['lesson_id'], $student_id)
                ];
            }

        }
        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 1
            ],
            'sort' => [
                'attributes' => ['lesson'],
            ],
        ]);
    }

//班主任成长日志按照时间查询
    public function actionFindbytime()
    {

    }

    protected function findModel($lesson_id)
    {
        $model = (new Query())->select('*')->from('{{%class_lesson}}')->where(['lesson_id' => $lesson_id])->one(Fun::getSiteDb());
        if ($model != null) {
            return $model;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }

    public function getLessonScore($lesson_score)
    {
        switch ($lesson_score) {
            case '1':
                return '你旷课了！鉴于你的表现，广场将不予奖励积分，希望下次及时请假';
                break;
            case '2':
                return '你今天迟到了！由于迟到所以没有奖励，希望下次努力！';
                break;
            case '3':
                return '欢呼！你的表现真不错！鉴于你的优秀表现，广场奖励积分    +3';
                break;
            case '4':
                return '欢呼！你的表现棒棒哒！鉴于你的优秀表现，广场奖励积分    +4';
                break;
            case '5':
                return '欢呼！你的表现超厉害！鉴于你的优秀表现，广场奖励积分    +5';
                break;
            case '6':
                return '欢呼！你真是小天才！你好棒！鉴于你的优秀表现，广场奖励积分    +6';
                break;
        }
        return '';
    }

    protected function getTel($customer_id)
    {
        $customer = Customer::find()->where(['id' => $customer_id])->one();
        return $customer['mobile'];
    }

    protected function getCourseList($student_id)
    {
        $dataArr = [];
        $classTeacher = (new Query())->select('*')->from('{{%order_sales}} a')
            ->leftJoin('{{%teacher}} b', 'a.teacher_id=b.id')
            ->where(['a.student_id' => $student_id])
            ->groupBy('a.teacher_id')
            ->all(Fun::getSiteDb());
        $classCourse = (new Query())->select('*')->from('{{%order_sales}} a')
            ->leftJoin('{{%course}} b', 'a.course_id=b.id')
            ->where(['a.student_id' => $student_id])
            ->groupBy('a.course_id')
            ->all(Fun::getSiteDb());
        foreach ($classTeacher as $k => $v) {
            foreach ($classCourse as $kk => $vv) {
                if ($v['order_id'] == $vv['order_id']) {
                    $dataArr[] = [
                        'course_name' => $v['name'],
                        'course_img' => $v['img'],
                        'teacher_name' => $vv['name'],
                    ];
                }
            }
        }
        return $dataArr;
    }

    protected function getTime($time)
    {
        $currentTime = strlen($time) == 3 ? substr($time, 0, 1) . ':' . substr($time, 1) : substr($time, 0, 2) . ':' . substr($time, 2);
        return $currentTime;
    }

    protected function getDay($day)
    {
        return \Yii::$app->formatter->asDate($day, 'yyyy-MM-dd');
    }

    protected function getTeacher($class_id)
    {
        $data = (new Query())->select('*')->from('{{%class_manage}} cm')
            ->leftJoin('{{%arrange_course}} ac', 'cm.code=ac.id')
            ->leftJoin('{{%teacher}} t', 'ac.teacher_id=t.id')
            ->where(['cm.class_id' => $class_id])
            ->one(Fun::getSiteDb());
        return $data['name'];
    }

    protected function getCredits($lesson_id, $student_id)
    {
        $data = [];
        $lessonMedia = (new Query())->select(['lm.m_type as m_type', 'm.file_path as url_path'])
            ->from('{{%lesson_media}} lm')
            ->leftJoin('{{%medias}} m', 'lm.medias_id=m.id')
            ->where(['lm.lesson_id' => $lesson_id, 'lm.student_id' => $student_id])
            ->all(Fun::getSiteDb());
        foreach ($lessonMedia as $k => $v) {
            $data[] = [
                'm_type' => $v['m_type'],
                'url_path' => $v['url_path']
            ];
        }
        return $data;
    }

    public function getLesson($class_id)
    {
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id, 'status' => 1])->all(Fun::getSiteDb());
        $classLessonArr = end($classLesson);
        return $classLessonArr['lesson'];

    }

    public function getContent($lesson_id, $student_id)
    {
        $lessonData = (new Query())->select('*')->from('{{%lesson_student}}')->where([
            'lesson_id' => $lesson_id, 'student_id' => $student_id
        ])->one(Fun::getSiteDb());
        $contentArr = [
            'evaluate_status' => (int)$lessonData['refouce_score'] == 0 ? 0 : 1,//评分状态
            'lesson_content' => $lessonData['lesson_content'],
            'lesson_fouce' => $lessonData['lesson_fouce'],
            'lesson_score' => $lessonData['lesson_score'],//评分
            'teacher_score' => $lessonData['teacher_score'],//对教师的评分
            'for_teacher' => $lessonData['for_teacher'],
            'refouce_score' => $lessonData['refouce_score'],//练习评分
            'refouce_answer' => $lessonData['refouce_answer'],
        ];
        return $contentArr;
    }

    protected function getAlreadyLesson($data)
    {
        $currentLessonArr = $totalLessonArr = [];
        $classLesson = ClassLesson::find()->where(['class_id' => $data->class_id])->asArray()->all();
        $ovo = isset($classLesson[0]['ovo']) ? $classLesson[0]['ovo'] : '';
        foreach ($classLesson as $k => $v) {
            if ($v['status'] == 1) {
                $currentLessonArr[] = $v;
            }
            if ($ovo == 0) {
                if (!in_array($v['status'], [2, 3, 4])) {
                    $totalLessonArr[] = $v;
                }
            } else {
                if (!in_array($v['status'], [2, 4])) {
                    $totalLessonArr[] = $v;
                }
            }
        }
        return ['ovo' => $ovo, 'already_lesson' => count($currentLessonArr) . '/' . count($totalLessonArr)];
    }

    protected function getSiteDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        \Yii::$app->set('db', $site_cache[$site]['db']);
    }

    protected function getDb($site_id)
    {
        $site_cache = Fun::cache('site_cache');
        foreach ($site_cache as $k => $v) {
            if ($site_id == $v['id']) {
                $site = $v['domain'];
            }
        }
        if ($site == null) return false;
        if (!isset($site_cache[$site])) return false;
        if (!isset($site_cache[$site]['db'])) return false;
        return \Yii::createObject($site_cache[$site]['db']);
    }

    /**
     * -------------------------------小风根据教师端pad单独写接口，免得影响到之前的那些功能
     */

    /*
     * 获取教师名下的课程学生信息列表
     */
    public function actionFindcoursestudent($user_id)
    {
        if (empty($user_id)) {
            return ['statusCode' => 200, 'items' => null];
        }
        $data = [];
        $admin = (new Query())->select('*')->from('{{%admin}}')
            ->where(['id' => $user_id])->one(Fun::getSiteDb());
        if (empty($admin) || empty($admin['teacher_id'])) {
            return ['statusCode' => 200, 'items' => null];
        }
        if ($admin['role'] == 'teache_teacher') {
            $teacher_id = $admin['teacher_id'];
            $goods_arrs = (new Query())->select(["goods_id", "max(IF(obj_type='class_count',value,'')) as class_count", "max(IF(obj_type='teacher_form',value,'')) as teacher_form", "max(IF(obj_type='teacher',attribute_id,'')) as teacher_id"])
                ->distinct()->from('{{%goods_attr}}')
                ->groupBy('goods_id')->having(['teacher_id' => $teacher_id])->all(Fun::getSiteDb());
            if (!empty($goods_arrs)) {
                foreach ($goods_arrs as $goodarr) {
                    $student_class = [];
                    $student_class['teache_form'] = $goodarr['teacher_form'];
                    $student_class['good_id'] = $goodarr['goods_id'];
                    $class_manage = null;
                    $good = (new Query())->select(['name', 'picture'])->from('{{%goods}}')->where(['id' => $goodarr['goods_id']])->one(Fun::getSiteDb());
                    if (!empty($good)) {
                        $student_class['name'] = $good['name'];
                        $student_class['picture'] = $good['picture'];
                    }
                    //只找已经开课了的
                    $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $goodarr['goods_id'], 'is_old' => 0, 'status' => 1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_students = (new Query())->select('id')->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->column(Fun::getSiteDb());
                        $student_class['student_num'] = count($class_students);
                        if (!empty($class_students)) {
                            $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->count('*', Fun::getSiteDb());
                            $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->andWhere(['status' => 1])->count('*', Fun::getSiteDb());
                            if (!empty($all_student_checks_count)) {
                                $student_class['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                            } else {
                                $student_class['attendance_rate'] = '0.00%';
                            }
                        }
                        $have_openedclass_num = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事
                        $student_class['opendclass_num_rate'] = $have_openedclass_num . '/' . $goodarr['class_count'];
                        //当前是停课还是复课,怎么判断呢？当前的表不大对劲啊，那就看看有没有存在停课状态的课程吧
                        $have_stopedclass = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id'], 'status' => 4])->one(Fun::getSiteDb());
                        if ($have_stopedclass) {
                            $is_stoppedclass = 1;
                        } else {
                            $is_stoppedclass = 0;
                        }
                        $student_class['is_stoppedclass'] = $is_stoppedclass;
                        $student_class['type'] = 'normal';
                        $data[] = $student_class;
                    }
                }
            }
            //以上得到的是正常课程或技教学的信息列表，下面要得到艺教学的学生课程管理
            $arrangements = (new Query())->select(['ar.*','a.*','c.name as course_name'])->from('{{%art_relation}} ar')
                ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
                ->leftJoin('{{%course}} c','c.id = a.course_id')
                ->where(['a.teacher_id'=>$teacher_id])
                ->orderBy('ar.lesson ASC')
                ->all(Fun::getSiteDb());
            if(!empty($arrangements)){
                foreach ($arrangements as $arrangement){
                    $student_class = [];
                    $student_class['teache_form'] = 1;//默认就一对多吧
                    $student_class['good_id'] = $arrangement['id'];
                    $student_class['name'] = $arrangement['course_name'];
                    $student_class['picture'] = '';
                    $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $arrangement['art_teaching_id'], 'is_old' => 0, 'status' => 1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_students = (new Query())->select('id')->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->column(Fun::getSiteDb());
                        $student_class['student_num'] = count($class_students);
                        if (!empty($class_students)) {
                            $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->count('*', Fun::getSiteDb());
                            $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->andWhere(['status' => 1])->count('*', Fun::getSiteDb());
                            if (!empty($all_student_checks_count)) {
                                $student_class['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                            } else {
                                $student_class['attendance_rate'] = '0.00%';
                            }
                        }
                        //虽然是一门课，但是每一节还不一样的老师。。。比例就不区分老师了吧，要不然怎么算上了百分之多少的课程
                        $have_openedclass_num = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事
                        $student_class['opendclass_num_rate'] = $have_openedclass_num . '/' . $arrangement['class_count'];
                        //当前是停课还是复课,怎么判断呢？当前的表不大对劲啊，那就看看有没有存在停课状态的课程吧
                        $have_stopedclass = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id'], 'status' => 4])->one(Fun::getSiteDb());
                        if ($have_stopedclass) {
                            $is_stoppedclass = 1;
                        } else {
                            $is_stoppedclass = 0;
                        }
                        $student_class['is_stoppedclass'] = $is_stoppedclass;
                        $student_class['type'] = 'art';
                        $data[] = $student_class;
                    }
                }
            }
            return ['statusCode' => 200, 'items' => $data];
        } elseif ($admin['role'] == 'class_teacher') {
            $classteacher_id = $admin['teacher_id'];
            $teacher_ids = (new Query())->select('id')->from('{{%teacher}}')->where(['parent_id'=>$classteacher_id])->column(Fun::getSiteDb());
            $goods_arrs = (new Query())->select(["goods_id", "max(IF(obj_type='class_count',value,'')) as class_count", "max(IF(obj_type='teacher_form',value,'')) as teacher_form", "max(IF(obj_type='teacher',attribute_id,'')) as teacher_id"])
                ->distinct()->from('{{%goods_attr}}')
                ->groupBy('goods_id')->having(['teacher_id' => $teacher_ids])->all(Fun::getSiteDb());
            if (!empty($goods_arrs)) {
                foreach ($goods_arrs as $goodarr) {
                    $student_class = [];
                    $student_class['teache_form'] = $goodarr['teacher_form'];
                    $student_class['good_id'] = $goodarr['goods_id'];
                    $class_manage = null;
                    $good = (new Query())->select(['name', 'picture'])->from('{{%goods}}')->where(['id' => $goodarr['goods_id']])->one(Fun::getSiteDb());
                    if (!empty($good)) {
                        $student_class['name'] = $good['name'];
                        $student_class['picture'] = $good['picture'];
                    }
                    //只找已经开课了的
                    $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $goodarr['goods_id'], 'is_old' => 0, 'status' => 1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_students = (new Query())->select('id')->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->column(Fun::getSiteDb());
                        $student_class['student_num'] = count($class_students);
                        if (!empty($class_students)) {
                            $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->count('*', Fun::getSiteDb());
                            $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->andWhere(['status' => 1])->count('*', Fun::getSiteDb());
                            if (!empty($all_student_checks_count)) {
                                $student_class['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                            } else {
                                $student_class['attendance_rate'] = '0.00%';
                            }
                        }
                        $have_openedclass_num = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事
                        $student_class['opendclass_num_rate'] = $have_openedclass_num . '/' . $goodarr['class_count'];
                        //当前是停课还是复课,怎么判断呢？当前的表不大对劲啊，那就看看有没有存在停课状态的课程吧
                        $have_stopedclass = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id'], 'status' => 4])->one(Fun::getSiteDb());
                        if ($have_stopedclass) {
                            $is_stoppedclass = 1;
                        } else {
                            $is_stoppedclass = 0;
                        }
                        $student_class['is_stoppedclass'] = $is_stoppedclass;
                        $student_class['type'] = 'normal';
                        $data[] = $student_class;
                    }
                }
            }
            //以上得到的是正常课程或技教学的信息列表，下面要得到艺教学的学生课程管理
            $arrangements = (new Query())->select(['ar.*','a.*','c.name as course_name'])->from('{{%art_relation}} ar')
                ->leftJoin('{{%arrangement}} a','a.id = ar.arrangement_id')
                ->leftJoin('{{%course}} c','c.id = a.course_id')
                ->where(['a.teacher_id'=>$teacher_ids])
                ->orderBy('ar.lesson ASC')
                ->all(Fun::getSiteDb());
            if(!empty($arrangements)){
                foreach ($arrangements as $arrangement){
                    $student_class = [];
                    $student_class['teache_form'] = 1;//默认就一对多吧
                    $student_class['good_id'] = $arrangement['id'];
                    $student_class['name'] = $arrangement['course_name'];
                    $student_class['picture'] = '';
                    $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $arrangement['art_teaching_id'], 'is_old' => 0, 'status' => 1])->one(Fun::getSiteDb());
                    if (!empty($class_manage)) {
                        $class_students = (new Query())->select('id')->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->column(Fun::getSiteDb());
                        $student_class['student_num'] = count($class_students);
                        if (!empty($class_students)) {
                            $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->count('*', Fun::getSiteDb());
                            $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['in', 'class_student_id', $class_students])->andWhere(['status' => 1])->count('*', Fun::getSiteDb());
                            if (!empty($all_student_checks_count)) {
                                $student_class['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                            } else {
                                $student_class['attendance_rate'] = '0.00%';
                            }
                        }
                        //虽然是一门课，但是每一节还不一样的老师。。。比例就不区分老师了吧，要不然怎么算上了百分之多少的课程
                        $have_openedclass_num = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事
                        $student_class['opendclass_num_rate'] = $have_openedclass_num . '/' . $arrangement['class_count'];
                        //当前是停课还是复课,怎么判断呢？当前的表不大对劲啊，那就看看有没有存在停课状态的课程吧
                        $have_stopedclass = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_manage['class_id'], 'status' => 4])->one(Fun::getSiteDb());
                        if ($have_stopedclass) {
                            $is_stoppedclass = 1;
                        } else {
                            $is_stoppedclass = 0;
                        }
                        $student_class['is_stoppedclass'] = $is_stoppedclass;
                        $student_class['type'] = 'art';
                        $data[] = $student_class;
                    }
                }
            }
            return ['statusCode' => 200, 'items' => $data];
        }

    }

    /*
     * 根据课程id获取学生课程管理详情
     * 要注意一对一和一对多？不用管了先
     */
    public function actionGetcoursestudentdetail($good_id,$type="normal")
    {
        if (empty($good_id)) {
            return ['statusCode' => 200, 'items' => null];
        }
        $data = [];
        if($type == 'normal'){
            $class_count = (new Query())->select('value')->from('{{%goods_attr}}')->where(['goods_id' => $good_id, 'obj_type' => 'class_count'])->one(Fun::getSiteDb());
            $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0])->one(Fun::getSiteDb());
            if (empty($class_manage)) {
                return ['statusCode' => 200, 'items' => null];
            }
            $class_students = (new Query())->select(['id', 'student_id'])->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->all(Fun::getSiteDb());
            if (empty($class_students)) {
                return ['statusCode' => 200, 'items' => null];
            }
            foreach ($class_students as $classstu) {
                $class_student = [];
                //得到学生的详细信息
                $student_detail = (new Query())->select(["stu.name as student_name", "cus.mobile as telephone", "stu.age as bornth", 'cus.logo as logo'])->from('{{%student}} stu')->leftJoin('{{%customer}} cus', 'cus.id=stu.customer_id')
                    ->where(['stu.id' => $classstu['student_id']])->one();
                $class_student['student_name'] = $student_detail['student_name'];
                $class_student['telephone'] = $student_detail['telephone'];
                $class_student['logo'] = $student_detail['logo'];
                if (!empty($student_detail['bornth'])) {
                    $year = intval(date('Y'));
                    $real_age = $year - intval($student_detail['bornth']);
                } else {
                    $real_age = '未知';
                }
                $class_student['real_age'] = $real_age;

                //得到该学生的针对课程出勤率
                $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['class_student_id' => $classstu['id']])->count('*', Fun::getSiteDb());
                $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['class_student_id' => $classstu['id'], 'status' => 1])->count('*', Fun::getSiteDb());
                if (!empty($all_student_checks_count)) {
                    $class_student['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                } else {
                    $class_student['attendance_rate'] = '0.00%';
                }
                $have_openedclass_num = (new Query())->from('{{%class_lesson}}')
                    ->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])
                    ->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事

                $class_student['opendclass_num_rate'] = $have_openedclass_num . '/' . $class_count['value'];
                $data[] = $class_student;
            }
        }elseif ($type == 'art'){
            //这时候的goods_id就不是商品id了而是arrangement的id
            $class_count = (new Query())->select('class_count')->from('{{%arrangement}}')->where(['id' => $good_id])->one(Fun::getSiteDb());
            $art_relation_id = (new Query())->select('art_teaching_id')->from('{{%art_relation}}')->where(['arrangement_id' => $good_id])->one(Fun::getSiteDb());
            $class_manage = (new Query())->select(['class_id'])->from('{{%class_manage}}')->where(['associate_id' => $art_relation_id['art_teaching_id'], 'is_old' => 0])->one(Fun::getSiteDb());
            if (empty($class_manage)) {
                return ['statusCode' => 200, 'items' => null];
            }
            $class_students = (new Query())->select(['id', 'student_id'])->from('{{%class_student}}')->where(['class_manage_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1, 2]])->all(Fun::getSiteDb());
            if (empty($class_students)) {
                return ['statusCode' => 200, 'items' => null];
            }
            foreach ($class_students as $classstu) {
                $class_student = [];
                //得到学生的详细信息
                $student_detail = (new Query())->select(["stu.name as student_name", "cus.mobile as telephone", "stu.age as bornth", 'cus.logo as logo'])->from('{{%student}} stu')->leftJoin('{{%customer}} cus', 'cus.id=stu.customer_id')
                    ->where(['stu.id' => $classstu['student_id']])->one();
                $class_student['student_name'] = $student_detail['student_name'];
                $class_student['telephone'] = $student_detail['telephone'];
                $class_student['logo'] = $student_detail['logo'];
                if (!empty($student_detail['bornth'])) {
                    $year = intval(date('Y'));
                    $real_age = $year - intval($student_detail['bornth']);
                } else {
                    $real_age = '未知';
                }
                $class_student['real_age'] = $real_age;

                //得到该学生的针对课程出勤率
                $all_student_checks_count = (new Query())->from('{{%student_check}}')->where(['class_student_id' => $classstu['id']])->count('*', Fun::getSiteDb());
                $attend_student_checks_count = (new Query())->from('{{%student_check}}')->where(['class_student_id' => $classstu['id'], 'status' => 1])->count('*', Fun::getSiteDb());
                if (!empty($all_student_checks_count)) {
                    $class_student['attendance_rate'] = round($attend_student_checks_count / $all_student_checks_count * 100, 2) . '%';
                } else {
                    $class_student['attendance_rate'] = '0.00%';
                }
                $have_openedclass_num = (new Query())->from('{{%class_lesson}}')
                    ->where(['class_id' => $class_manage['class_id']])->andWhere(['in', 'status', [1]])
                    ->count('*', Fun::getSiteDb());//课程总课次可以在这里得到，也可以从goods_arr得到，我就从goodsarr里面得了还省事

                $class_student['opendclass_num_rate'] = $have_openedclass_num . '/' . $class_count['class_count'];
                $data[] = $class_student;
            }
        }
        return ['statusCode' => 200, 'items' => $data];
    }

    /*
     * 教师端确认停课
     * 停课的需求是针对今天以后的课程进行停课，没啥请假不请假啥的就全都改为停课的状态
     */
    public function actionSuspendclass($class_id, $teache_id)
    {
        /*要注意延课的情况*/
        if (empty($class_id) || empty($teache_id)) {
            return ['statusCode' => 200, 'items' => null];
        }
        $postData = \Yii::$app->request->post();
        $reason = ArrayHelper::keyExists('reason', $postData) ? $postData['reason'] : '';
        $remark = ArrayHelper::keyExists('remark', $postData) ? $postData['remark'] : '';
        $stopreason_arr = ['teache_id' => $teache_id, 'reason' => $reason, 'remark' => $remark, 'status' => 4];
        $stopreason = serialize($stopreason_arr);
        $date_addoneday = date("Y-m-d", strtotime("+1 day"));
        $addoneday_time = strtotime($date_addoneday);
        //$ddd = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', $addoneday_time])->all(Fun::getSiteDb());"id=:id", array(':id' => $id)['class_id' => $class_id,'class_date'=>$addoneday_time]
        Fun::getSiteDb()->createCommand()->update('{{%class_lesson}}', ['status' => 4, 'info' => $stopreason], "class_id=:classid and class_date >= :classdate", [':classid' => $class_id, ':classdate' => $addoneday_time])->execute();
        $data = ['status' => 4, 'info' => '停课成功'];
        return ['statusCode' => 200, 'items' => $data];
    }

    /**
     * @param $good_id
     * @return array
     * 教师端确认复课返回信息 这一块没有什么用，因为不是复课复一门，而是复课全部
     */
    public function actionRegain($class_id, $time)
    {
        $lessonArr = [];
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->all(Fun::getSiteDb());
        foreach ($classLesson as $k => $v) {
            if ($v['status'] == 4) {
                $lessonArr[] = $v;
            }
        }
        if (empty($lessonArr)) {
            try {
                throw new NotFoundHttpException('当前没有可恢复课程');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $data['items'] = [
            'time' => $time,
            'info' => '您选择从' . $time . '日开始复课'
        ];
        return $data;
    }

    /*
     * 复课操作
     * 这部分的逻辑就是将停课的课程根据今天的时间来进行下一个周几的上课时间安排，
     * 比如本来停课的节是周三，然后今天开始的下一个周三就是那个课程复课的时间
     */
    public function actionRegainclass($class_id, $teache_id, $time = '')
    {
        $class_lessons = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id, 'status' => 4])->all(Fun::getSiteDb());
        if (count($class_lessons) == 0) {
            try {
                throw new NotFoundHttpException('您当前没有处在停课状态的课程');
            } catch (NotFoundHttpException $e) {
                return ['statusCode' => 0, 'message' => 'error', 'items' => $e->getMessage()];
            }
        }
        $recover = ['teache_id' => $teache_id, 'remark' => '教师复课', 'status' => 6];
        $now_time = time();
        $weeks = array("Monday" => 0, "Tuesday" => 0, "Wednesday" => 0, "Thursday" => 0, "Friday" => 0, "Saturday " => 0, "Sunday" => 0);
        foreach ($class_lessons as $k => $class_lesson) {
            //一周多节课，不能直接加7天啦这玩意有大bug到时候全局搜7来讨论个解决方案
            $origin_classtime = $class_lesson['class_date'];//这个是课程原有的上课时间
            $origin_week = date("l", $origin_classtime);
            $weeks[$origin_week] = $weeks[$origin_week] + 1;
            //获取下周的某周几
            $after_classtime = strtotime("+" . $weeks[$origin_week] . " week last " . $origin_week);//当前时间加上对应的下周or下下($weeks[$Origin_week])周的周几$origin_week
            if ($k > 0 && !empty($class_lessons[$k - 1]['class_date'])) {

                while ($after_classtime < $class_lessons[$k - 1]['class_date']) {//当增加的时间比上一节课的时间还小，那就要继续增加一个周,
                    //貌似如果按照一周固定的周几上课应该没啥影响,测试的时候是随机的上课情况就不行了，为了以后出现啥变动时间导致不符合当前规则的情况还是加上这个功能吧
                    $weeks[$origin_week] = $weeks[$origin_week] + 1;
                    $after_classtime = strtotime("+" . $weeks[$origin_week] . " week last " . $origin_week);
                }
            }
            $class_lessons[$k]['class_date'] = $after_classtime;//\Yii::$app->formatter->asTimestamp($time) + $k * 7 * 24 * 60 * 60;
            $class_lessons[$k]['lesson_id'] = $class_lesson['lesson_id'];
            Fun::getSiteDb()->createCommand()->update('{{%class_lesson}}', [
                'class_date' => $class_lessons[$k]['class_date'], 'status' => 6, 'info' => serialize($recover)//或许这个状态不用改成复课直接就正常状态？？算了还是按照数据库设计的吧，其他地方关于上课的把复课的状态也按正常的状态来上课
            ], ['lesson_id' => $class_lessons[$k]['lesson_id']])->execute();
        }
        $data = ['status' => 6, 'info' => '申请复课成功'];

        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }

    /*
     * 教师端一键延课-1 首先要将上课时间列表显示出来，直接复制了gettime的方法来改的
     */
    public function actionGetclasstime($good_id,$type='normal')
    {
        if($type == 'art'){
            $art_relation = (new Query())->select('art_teaching_id')->from('{{%art_relation}}')->where(['arrangement_id'=>$good_id])->one(Fun::getSiteDb());
            $good_id = $art_relation['art_teaching_id'];
            $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0,'type'=>2])->one(Fun::getSiteDb());
        }else{
            $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0,'type'=>1])->one(Fun::getSiteDb());
        }

        $timeArr = [];
        /*为什么只获取前5条数据，只能前5节课延课？*/
        $class_id = $class_manage['class_id'];
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id, 'status' => 0])->limit(5)->all(Fun::getSiteDb());
        foreach ($classLesson as $k => $v) {
            $timeArr[] = [
                'timestamp' => $v['class_date'],
                'time' => \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd')
            ];
        }
        return ['statusCode' => 200, 'items' => $timeArr];
    }

    public function actionGetclassid($good_id,$type='normal')
    {
        if($type == 'art'){
            $art_relation = (new Query())->select('art_teaching_id')->from('{{%art_relation}}')->where(['arrangement_id'=>$good_id])->one(Fun::getSiteDb());

            $good_id = $art_relation['art_teaching_id'];
            $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0,'type'=>2])->one(Fun::getSiteDb());
        }else{
            $class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0,'type'=>1])->one(Fun::getSiteDb());
        }
        //$class_manage = (new Query())->select('*')->from('{{%class_manage}}')->where(['associate_id' => $good_id, 'is_old' => 0])->one(Fun::getSiteDb());
        if (!empty($class_manage)) {
            $data = $class_manage['class_id'];
        } else {
            $data = null;
        }
        return ['statusCode' => 200, 'items' => $data];
    }

    /*选中了延课时间之后给出的提示信息，延课和请假有啥分别，延课就是请假啦*/
    public function actionDelayinfo($class_id, $time)
    {
        if (empty($class_id)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程选择不能为空'];
        }
        $tomorrow_time = strtotime(date("Y-m-d", strtotime('+1 day')));//获取第二天的凌晨时间戳,仅仅能将第二天之后的课程进行延课操作
        $classLessons = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', $tomorrow_time])
            ->all(Fun::getSiteDb());
        if (empty($classLessons)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程不存在可延课的课次'];
        } else {
            $lesson_infos = [];
            foreach ($classLessons as $class_lesson) {
                $lesson_infos[] = '第' . $class_lesson['lesson'] . '节课，上课时间为' . date('Y-m-d', $class_lesson['class_date']);
            }
            return ['statusCode' => 200, 'message' => 'success', 'items' => $lesson_infos];
        }
    }

    public function actionDelayinfo_bak201170518($class_id, $time)
    {
        if (empty($class_id) || empty($time)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程和课时选择不能为空'];
        }
        $alreadyTimeArr = $remainTimeArr = $lessonArr = [];
        $lessonStatus = '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])
            ->all(Fun::getSiteDb());
        //下面的逻辑要修改一下
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd')) {
                $lessonArr = $v;
                $lessonStatus = $v['status'];
                if ($lessonStatus == 2) {
                    try {
                        throw new ForbiddenHttpException('您选的课时课程第' . $v['lesson'] . '节课已被延课，无需重复选择');
                    } catch (ForbiddenHttpException $e) {
                        return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
                    }
                }
                if ($lessonStatus != 0 && $lessonStatus != 6) {
                    try {
                        throw new ForbiddenHttpException('您选的课时课程第' . $v['lesson'] . '节课不符合未上课的延课条件，请正确选择');
                    } catch (ForbiddenHttpException $e) {
                        return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
                    }
                }
            }
            if ($v['status'] == 1) {//正在上课
                $alreadyArr[] = $v;
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd');
            }
            if ($v['status'] != 1) {//
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd');
            }
            if ($v['status'] == 0) {
                $classTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd');
                $classArr[] = $v;
            }
        }
        if (in_array($time, $alreadyTimeArr)) {//已经上课了
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能延课,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {//选择的时间不再未上课也不在不上课的列表里面
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        //改改改改改改改改改改改改改改,这里的时间显示要根据传过来的时间来进行判断选择，但是现在的app端的时间选框还不好使，没法确定
        $year = substr($time, 0, 4);
        $monthData = substr($time, stripos($time, '-') + 1, 2);
        $month = strstr($time, '-') ? substr($monthData, 0, 1) : substr($monthData, 0, 2);
        $day = substr($time, strripos($time, '-') + 1);
        $data = [
            'time' => $time,
            'info' => '您当前选择的请假日期为' . $year . '年' . $monthData . '月' . $day . '日,为该课程的第' . $lessonArr['lesson'] . '节课'
        ];
        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }

    /*
     * 教师端一键延课-2 进行对应课程时间的延迟操作
     */
    public function actionDelayclassconfirm($class_id, $time, $teache_id)
    {
        if (empty($class_id) || empty($time)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程和延课时间不能为空'];
        }
        /*
         * 开发流程，
         * 1. 先获取当前课程的上课时间排在今天之后的
         * 2. 然后从头循环上课列表，将上课时间更改为以当前提交的延课时间为基准的时间，同时状态和info也要更改
         */
        $tomorrow_time = strtotime(date("Y-m-d", strtotime('+1 day')));//获取第二天的凌晨时间戳,仅仅能将第二天之后的课程进行延课操作
        $classLessons = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', $tomorrow_time])
            ->all(Fun::getSiteDb());
        //$weeks = array("Monday" => 0, "Tuesday" => 0, "Wednesday" => 0, "Thursday" => 0, "Friday" => 0, "Saturday " => 0, "Sunday" => 0);
        $weeks = array("Monday" => ['value'=>0,'day'=>''], "Tuesday" => ['value'=>0,'day'=>''], "Wednesday" => ['value'=>0,'day'=>''], "Thursday" => ['value'=>0,'day'=>''], "Friday" => ['value'=>0,'day'=>''], "Saturday " => ['value'=>0,'day'=>''], "Sunday" => ['value'=>0,'day'=>'']);

        $based_time = strtotime($time);
        $classLessonArr = ['teache_id' => $teache_id, 'remark' => '教师延课', 'status' => 2];
        if (!empty($classLessons)) {
            foreach ($classLessons as $k => $class_lesson) {
                //一周多节课，不能直接加7天啦这玩意有大bug到时候全局搜7来讨论个解决方案
                $origin_classtime = $class_lesson['class_date'];//这个是课程原有的上课时间
                $origin_week = date("l", $origin_classtime);
                $day = date('Y-m-d',$origin_classtime);
                $hour = date('H',$origin_classtime);$min = date('i',$origin_classtime);$second = date('s',$origin_classtime);
                if($weeks[$origin_week]['day'] != $day){//当不是同一天了说明换了下个周几了，这时候才能进行周几的相加
                    $weeks[$origin_week]['day'] = $day;
                    $weeks[$origin_week]['value'] = $weeks[$origin_week]['value'] + 1;
                }
                //获取下周的某周几
                $after_classtime = strtotime("+" . $weeks[$origin_week]['value']  . " week ".$hour." hours ".$min." minutes ".$second." seconds last " . $origin_week, $based_time);//当前时间加上对应的下周or下下($weeks[$Origin_week])周的周几$origin_week
                if ($k > 0 && !empty($class_lessons[$k - 1]['class_date'])) {
                    while ($after_classtime < $class_lessons[$k - 1]['class_date']) {//当增加的时间比上一节课的时间还小，那就要继续增加一个周……再继续开发我都忘了啥时候会有这种情况，已经上课了？
                        $weeks[$origin_week] = $weeks[$origin_week] + 1;
                        $after_classtime = strtotime("+" . $weeks[$origin_week] . " week ".$hour." hours ".$min." minutes ".$second." seconds last " . $origin_week, $based_time);
                    }
                }
                $class_lessons[$k]['class_date'] = $after_classtime;//\Yii::$app->formatter->asTimestamp($time) + $k * 7 * 24 * 60 * 60;
                $class_lessons[$k]['lesson_id'] = $class_lesson['lesson_id'];
                Fun::getSiteDb()->createCommand()->update('{{%class_lesson}}', [
                    'class_date' => $class_lessons[$k]['class_date'], 'status' => 7, 'info' => serialize($classLessonArr)//或许这个状态不用改成复课直接就正常状态？？算了还是按照数据库设计的吧，其他地方关于上课的把复课的状态也按正常的状态来上课
                ], ['lesson_id' => $class_lessons[$k]['lesson_id']])->execute();
            }
        }
        $data = ['status' => 7, 'info' => '延课成功'];

        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];

    }

    public function actionDelayclassconfirm_bak20170518($class_id, $time, $teache_id)
    {
        if (empty($time) || empty($class_id)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程和课时选择不能为空'];
        }
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])
            ->all(Fun::getSiteDb());
        if (empty($classLesson)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '不存在对应的班级课程'];
        }
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd')) {
                $lessonId = $v['lesson_id'];
                $classLessonArr = ['teache_id' => $teache_id, 'remark' => '教师延课', 'status' => 2];
                Fun::getSiteDb()->createCommand()->update(
                    '{{%class_lesson}}', ['status' => 2, 'info' => serialize($classLessonArr)], ['lesson_id' => $lessonId]
                )->execute();
                //延课了的话就要重新添加对应的课时课程，那对应的student_check、lesson_student，什么的应该也要添加记录或者修改记录？吧
                $delayed_classlesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['lesson_id' => $lessonId])->one(Fun::getSiteDb());
                $max_classdate = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_id])->max('class_date', Fun::getSiteDb());
                $max_lesson = (new Query())->from('{{%class_lesson}}')->where(['class_id' => $class_id])->max('lesson', Fun::getSiteDb());
                $last_newclassday = $max_classdate + 7 * 24 * 60 * 60;//以后一周多节课不能这样写啦就
                $insert_classlesson_arr = [
                    'class_id' => (int)$class_id,
                    'class_date' => (int)$last_newclassday,
                    'start_time' => (int)$delayed_classlesson['start_time'],
                    'end_time' => (int)$delayed_classlesson['end_time'],
                    'lesson' => $max_lesson + 1,
                    'title' => $delayed_classlesson['title'],
                    'status' => 0,
                    'ovo' => (int)$delayed_classlesson['ovo'],
                ];
                Fun::getSiteDb()->createCommand()->insert('{{%class_lesson}}', $insert_classlesson_arr)->execute();
                $last_insert = (new Query())->select('lesson_id')->from('{{%class_lesson}}')->where(['class_id' => $class_id, 'lesson' => $max_lesson + 1])->one(Fun::getSiteDb());
                $insert_classlesson_id = $last_insert['lesson_id'];
                //将之前属于当前班级课程的记录更改为最新请假后的班级课程排课
                Fun::getSiteDb()->createCommand()->update('{{%student_check}}', ['class_lesson_id' => $insert_classlesson_id], ['class_lesson_id' => $lessonId])->execute();
                Fun::getSiteDb()->createCommand()->update('{{%lesson_student}}', ['lesson_id' => $insert_classlesson_id], ['lesson_id' => $lessonId])->execute();
            }
        }
        return ['statusCode' => 200, 'message' => 'success', 'items' => '成功延课'];
    }

    /**
     * 找老师代课的操作
     * 先选择代课时间，然后选择代课老师的信息
     * 要有教师姓名，联系电话和备注，放到info里面
     * 时间列表的获取用Getclasstime方法
     */
    /*获取可进行代课的课节课次*/
    public function actionGetsubstituteclass($class_id)
    {
        $tomorrow_time = strtotime("+1 day");
        $class_lessons = (new Query())->select('*')->from('{{%class_lesson}}')->where(['class_id' => $class_id])->andWhere(['>=', 'class_date', $tomorrow_time])->all(Fun::getSiteDb());
        foreach ($class_lessons as $k => $cl) {
            if (!empty($cl['class_date'])) {
                $classdateformat = date('Y-m-d', $cl['class_date']);
                $cl['classdateformat'] = $classdateformat;
                $week = date("w", $cl['class_date']);
                $cl['week'] = $this->getClassweek($week);
                $class_lessons[$k] = $cl;
            }
        }
        if (!empty($class_lessons)) {
            return ['statusCode' => 200, 'message' => 'success', 'items' => $class_lessons];
        } else {
            return ['statusCode' => 200, 'message' => 'error', 'items' => '可代课的课程节次为空'];
        }
    }

    public function getClassweek($value = 0)
    {
        switch ($value) {
            case 1:
                return '星期一';
                break;
            case 2:
                return '星期二';
                break;
            case 3:
                return '星期三';
                break;
            case 4:
                return '星期四';
                break;
            case 5:
                return '星期五';
                break;
            case 6:
                return '星期六';
                break;
            case 7:
                return '星期日';
                break;
            default:
                return '未知';
        }
        return '未知';
    }

    /*选择完时间之后给出时间的详细信息第几节课，如果不可用给出错误提示信息*/
    public function actionSubstituteclassinfo_bak($class_id, $time)
    {
        if (empty($class_id) || empty($time)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程和课时选择不能为空'];
        }
        $alreadyTimeArr = $remainTimeArr = $lessonArr = [];
        $lessonStatus = '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['class_id' => $class_id])
            ->all(Fun::getSiteDb());
        //下面的逻辑要修改一下
        foreach ($classLesson as $k => $v) {
            if ($time == \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd')) {
                $lessonArr = $v;
                $lessonStatus = $v['status'];
                if ($lessonStatus == 5) {
                    try {
                        throw new ForbiddenHttpException('您选的课时课程第' . $v['lesson'] . '节课已被代课，无需重复选择');
                    } catch (ForbiddenHttpException $e) {
                        return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
                    }
                }
                if ($lessonStatus != 0 && $lessonStatus != 6) {
                    try {
                        throw new ForbiddenHttpException('您选的课时课程第' . $v['lesson'] . '节课不符合未上课的代课条件，请正确选择');
                    } catch (ForbiddenHttpException $e) {
                        return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
                    }
                }
            }
            if ($v['status'] == 1) {//正在上课
                $alreadyArr[] = $v;
                $alreadyTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd');
            }
            if ($v['status'] != 1) {//
                $remainArr[] = $v;
                $remainTimeArr[] = \Yii::$app->formatter->asDate($v['class_date'], 'yyyy-MM-dd');
            }
        }
        if (in_array($time, $alreadyTimeArr)) {//已经上课了
            try {
                throw new ForbiddenHttpException('您选则该时间的课时已结束,不能延课,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if (!in_array($time, $alreadyTimeArr) && !in_array($time, $remainTimeArr)) {//选择的时间不再未上课也不在不上课的列表里面
            try {
                throw new ForbiddenHttpException('您选的时间和课程安排的时间不对应,不能请假,请选择正确的时间');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        //改改改改改改改改改改改改改改,这里的时间显示要根据传过来的时间来进行判断选择，但是现在的app端的时间选框还不好使，没法确定
        $year = substr($time, 0, 4);
        $monthData = substr($time, stripos($time, '-') + 1, 2);
        $month = strstr($time, '-') ? substr($monthData, 0, 1) : substr($monthData, 0, 2);
        $day = substr($time, strripos($time, '-') + 1);
        $data = [
            'time' => $time,
            'info' => '您当前选择的请假日期为' . $year . '年' . $monthData . '月' . $day . '日,为该课程的第' . $lessonArr['lesson'] . '节课'
        ];
        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }

    public function actionSubstituteclassinfo($lesson_id)
    {
        if (empty($lesson_id)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课次选择不能为空'];
        }
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')
            ->where(['lesson_id' => $lesson_id])
            ->one(Fun::getSiteDb());
        $lessonStatus = $classLesson['status'];
        if ($lessonStatus == 5) {
            try {
                throw new ForbiddenHttpException('您选的课时课程第' . $classLesson['lesson'] . '节课已被代课，无需重复选择');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        if ($lessonStatus != 0 && $lessonStatus != 6 && $lessonStatus != 7) {//当课程正在停课的话不能够进行代课,如果已经被延课了是可以正常进行代课操作的
            try {
                $reason = '';
                switch ($lessonStatus) {
                    case 1:
                        $reason = '已上课';
                        break;
                    case 2:
                        $reason = '教师已请假';
                        break;
                    case 4:
                        $reason = '教师停课';
                        break;
                    default:
                        $reason = '不符合未上课';
                        break;
                }
                throw new ForbiddenHttpException('您选的课时课程第' . $classLesson['lesson'] . '节课处于' . $reason . '的状态，不符合代课条件，请正确选择');
            } catch (ForbiddenHttpException $e) {
                return ['statusCode' => 200, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        //改改改改改改改改改改改改改改,这里的时间显示要根据传过来的时间来进行判断选择，但是现在的app端的时间选框还不好使，没法确定
        $date = date('Y-m-d', $classLesson['class_date']);
        $data = [
            'info' => '您当前选择的请假日期为' . $date . ',为该课程的第' . $classLesson['lesson'] . '节课'
        ];
        return ['statusCode' => 200, 'message' => 'success', 'items' => $data];
    }

    /*
     * 提交代课信息来进行代课操作
     */
    public function actionSubstituteclasssubmit($lesson_id, $teache_id)
    {
        if (empty($lesson_id)) {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '课程课次选择不能为空'];
        }
        $data = \Yii::$app->request->post();
        $teacherName = ArrayHelper::keyExists('teacher_name', $data) ? $data['teacher_name'] : '';
        $teacherTel = ArrayHelper::keyExists('teacher_tel', $data) ? $data['teacher_tel'] : '';
        $remark = ArrayHelper::keyExists('remark', $data) ? $data['remark'] : '';
        $classLesson = (new Query())->select('*')->from('{{%class_lesson}}')->where(['lesson_id' => $lesson_id])->one(Fun::getSiteDb());
        if (!empty($classLesson)) {
            $replace = [
                'teache_id' => $teache_id, 'teacher_name' => $teacherName, 'teacher_tel' => $teacherTel, 'remark' => $remark, 'status' => 5
            ];
            Fun::getSiteDb()->createCommand()->update('{{%class_lesson}}', [
                'info' => serialize($replace), 'status' => 5
            ], ['lesson_id' => $lesson_id])->execute();
            return ['statusCode' => 200, 'message' => 'success', 'items' => '成功申请代课'];
        } else {
            return ['statusCode' => 200, 'message' => 'error', 'result' => '班级课程列表为空'];
        }

    }


}